//
//  USOurListController.m
//  us
//
//  Created by karry on 2025/5/7.
//

#import "USOurListController.h"
#import "USOurListCell.h"
#import "USAddOurListGroupController.h"
#import "USAddOurListSubListController.h"
#import "USListModel.h"
@interface USOurListController ()<UICollectionViewDelegate,UICollectionViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>


@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong) NSMutableArray <USListModel *>*daysList;

@end

@implementation USOurListController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.prefersLargeTitles = YES;
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"清单";
    
    self.navigationController.navigationBar.prefersLargeTitles = YES;
    
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAutomatic;
    
    self.navigationController.navigationBar.largeTitleTextAttributes = @{
        NSFontAttributeName: [UIFont boldSystemFontOfSize:32],
        NSForegroundColorAttributeName: [UIColor labelColor]
    }; 
    
    [self setupView];
}

- (void)loadData{
    [super loadData];
    
    [[EMNetWork shareManager] em_post:API_DailyChallengeList
                               params:@{@"sharedSpaceId":USUser.user.sharedSpaceId?:@""}
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            [self loadingFailed];
            return;
        }
        NSArray *list = [USListModel mj_objectArrayWithKeyValuesArray:api.data[@"sweetChallengeList"]];
        
        [self.daysList removeAllObjects];
        
        [self.daysList addObjectsFromArray:list];
        if (list.count == 0) {
            self.dataState = EmptyDataStateNoData;
        }
        
        [self.collectionView reloadData];
        [self.collectionView reloadEmptyDataSet];
        
        
    } fail:^{
        
        
    }];
    
}

- (void)deleteListAtIndex:(NSIndexPath *)indexPath{
    USListModel *model = self.daysList[indexPath.row];
    
    [[EMNetWork shareManager] em_post:API_DailyChallengeDelete
                               params:@{@"sweetChallengeId":model.sweetChallengeId?:@""}
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            [self loadingFailed];
            return;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView performBatchUpdates:^{
                [self.daysList removeObjectAtIndex:indexPath.row];
                [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
            } completion:nil];
            
            if (self.daysList.count == 0) {
                self.dataState = EmptyDataStateNoData;
            }
            
            [self.collectionView reloadData];
            [self.collectionView reloadEmptyDataSet];
            
        });
    } fail:^{
        
        
    }];
    
}

- (NSMutableArray <USListModel *>*)daysList {
    if (_daysList == nil) {
        _daysList = [NSMutableArray array];
    }
    return _daysList;
}
- (void)setupView{
    
    CGFloat margin = 16;
    
    CGFloat itemW = (self.view.bounds.size.width - margin * 3)/2.f;
    CGFloat itemH = itemW * 145/168;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(itemW, itemH);
    layout.minimumLineSpacing = margin;
    layout.sectionInset = UIEdgeInsetsMake(margin, margin, margin, margin);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.collectionView.backgroundColor = UIColor.clearColor;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.emptyDataSetSource = self;
    self.collectionView.emptyDataSetDelegate = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"USOurListCell" bundle:nil] forCellWithReuseIdentifier:@"USOurListCellId"];
    [self.view addSubview:self.collectionView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_add"] style:UIBarButtonItemStylePlain target:self action:@selector(addAction:)];
    
}


#pragma mark - action
- (void)addAction:(id)sender{
    [USFeedbackTool impactSoft];
    
    USAddOurListGroupController *vc = [USAddOurListGroupController new];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)editAtIndexPath:(NSIndexPath *)indexPath{
    
    [USFeedbackTool impactSoft];
    USListModel *model = self.daysList[indexPath.row];
    
    USAddOurListGroupController *vc = [USAddOurListGroupController new];
    vc.isEdit = YES;
    vc.dayModel = model;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

- (void)deleteAtIndexPath:(NSIndexPath *)indexPath{
    
    [USFeedbackTool impactSoft];
    
    
    MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"确定删除此清单吗" detailTitle:@"此操作不可撤销哦，请谨慎操作" contentView:nil leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
    alert.titleLabel.textColor = [UIColor jk_colorWithHex:0xF36257];
    @weakify(self)
    alert.didClickIndexBlock = ^(NSInteger index) {
        @strongify(self)
        if (index == 1) {
            [self deleteListAtIndex:indexPath];
        }
    };
    
    [alert show];
}



#pragma mark - <UICollectionViewDelegate,UICollectionViewDataSource>
- (nullable UIContextMenuConfiguration *)collectionView:(UICollectionView *)collectionView contextMenuConfigurationForItemAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point API_AVAILABLE(ios(13.0)){
    
    return  [UIContextMenuConfiguration configurationWithIdentifier:nil previewProvider:nil actionProvider:^UIMenu * _Nullable(NSArray<UIMenuElement *> * _Nonnull suggestedActions) {
        
        @weakify(self)
        UIAction *action = [UIAction actionWithTitle:@"编辑" image:[UIImage systemImageNamed:@"square.and.pencil"] identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
            @strongify(self)
            [self editAtIndexPath:indexPath];
        }];
        
        UIAction *delete = [UIAction actionWithTitle:@"删除清单" image:[UIImage systemImageNamed:@"trash"] identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
            @strongify(self)
            [self deleteAtIndexPath:indexPath];
            
        }];
        
        delete.attributes = UIMenuElementAttributesDestructive;
        
        UIMenu *menu = [UIMenu menuWithTitle:@"" image:[UIImage new] identifier:nil options:UIMenuOptionsDisplayInline children:@[action,delete]];
        
        return menu;
    }];
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    [USFeedbackTool impactSoft];
    
    USAddOurListSubListController *vc = [USAddOurListSubListController new];
    USListModel *model = self.daysList[indexPath.row];
    vc.listModel = model;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.daysList.count;
    
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    USOurListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USOurListCellId" forIndexPath:indexPath];
    
    USListModel *model = self.daysList[indexPath.row];
    
    cell.listView.color = [UIColor jk_colorWithHexString:model.color];
    
    cell.listView.titleLab.text = model.challengeTitle;
    if (model.taskCount == 0) {
        cell.listView.progressView.progress = 0.0;
    }else{
        cell.listView.progressView.progress = model.completedTaskCount * 1.0/model.taskCount * 1.0;
    }
    cell.listView.progressLab.text = [NSString stringWithFormat:@"%li/%li",model.completedTaskCount,model.taskCount];
    return cell;
    
}


#pragma mark - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate


- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView{
    
    if (self.dataState == EmptyDataStateLoading) {
        UIView *contentView = [UIView new];
        contentView.frame = CGRectMake(0, 0, self.view.jk_width, 200);
        
        NSString *gifPath = [[NSBundle mainBundle] pathForResource:@"load_page" ofType:@"gif"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:nil];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.frame = CGRectMake(0, 0, 200, 200);
        [imageView sd_setImageWithURL:[NSURL fileURLWithPath:gifPath]];
        
        [contentView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(200);
            make.center.mas_equalTo(contentView);
        }];
        
        return contentView;
    }
    USEmptyView *emptyView = [[USEmptyView alloc] initWithFrame:CGRectMake(0, 0, self.view.jk_width, 0)];
    emptyView.image = [UIImage imageNamed:@"memorialDay_Empty"];
    emptyView.title = @"添加你们的小事或愿望清单组";
    emptyView.btnTitle = @"添加";
    emptyView.userInteractionEnabled = YES;
    [emptyView.btn addTarget:self action:@selector(addAction:) forControlEvents:UIControlEventTouchUpInside];
    return emptyView;
    
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    
    
    return YES; // 允许点击
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    
    
    return YES; // 避免 scrollView 吃掉 touch 事件
}



@end
